package nl.ajonker.railroad.ui;

import nl.ajonker.railroad.sl.SwitchService;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class NetworkPanel extends JPanel {

    private final JLabel hostLabel = new JLabel("Host: ");
    private final JTextField hostField = new JTextField(20);
    private final JLabel portLabel = new JLabel("Port: ");
    private final JTextField portField = new JTextField(5);
    private final JButton saveButton = new JButton("Save");
    private final JLabel ipLabel = new JLabel();

    public NetworkPanel(final SwitchService switchService) {
        add(hostLabel);
        add(hostField);
        add(portLabel);
        add(portField);
        add(saveButton);
        add(ipLabel);

        hostField.setText(switchService.getHostname());
        portField.setText(String.valueOf(switchService.getPort()));
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Integer port = null;
                if (StringUtils.isNumeric(portField.getText()))
                    port = Integer.parseInt(portField.getText());
                switchService.setAddress(hostField.getText(), port);
            }
        });
    }
}
